package com.example.demo.controller;


import com.example.demo.dto.RedisConfigDto;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

import java.util.Set;
import java.util.TreeSet;

@RestController
public class RedisController {

    @PostMapping("redis/connect")
    public String connectRedis(@Validated @RequestBody RedisConfigDto redisConfigDto){
        if(redisConfigDto.getSentinels() == null){
            throw new RuntimeException("sentinels不能为空");
        }
        if(redisConfigDto.getMaster() == null){
            throw new RuntimeException("master不能为空");
        }
        if(redisConfigDto.getPwd() == null){
            throw new RuntimeException("密码不能为空");
        }
        JedisSentinelPool pool = null;
        Jedis jedis = null;
        try {
            pool = new JedisSentinelPool
                    (redisConfigDto.getMaster(), redisConfigDto.getSentinels(), redisConfigDto.getPwd());
// 永远返回的都是 Master 连接
            jedis = pool.getResource();
            Set<String> keys = jedis.keys("*");
            if (keys.iterator().hasNext()) {
                return keys.iterator().next();
            }
        }finally {
            if(jedis != null){
                jedis.close();
            }
            if(pool != null){
                pool.close();
            }
        }

        return null;
    }

    @PostMapping("redis/cmd")
    public String cmdRedis(@Validated @RequestBody RedisConfigDto redisConfigDto){
        if(redisConfigDto.getSentinels() == null){
            throw new RuntimeException("sentinels不能为空");
        }
        if(redisConfigDto.getMaster() == null){
            throw new RuntimeException("master不能为空");
        }
        if(redisConfigDto.getPwd() == null){
            throw new RuntimeException("密码不能为空");
        }
        JedisSentinelPool pool = null;
        Jedis jedis = null;
        try {
            pool = new JedisSentinelPool
                    (redisConfigDto.getMaster(), redisConfigDto.getSentinels(), redisConfigDto.getPwd());
// 永远返回的都是 Master 连接
            jedis = pool.getResource();
            Set<String> keys = jedis.keys("*");
            if (keys.iterator().hasNext()) {
                return keys.iterator().next();
            }
        }finally {
            if(jedis != null){
                jedis.close();
            }
            if(pool != null){
                pool.close();
            }
        }

        return null;
    }
}
